package com.ncst.mvcweb.controller;

import com.ncst.mvcweb.entity.*;
import com.ncst.mvcweb.service.ProductOrderService;
import com.ncst.mvcweb.service.ProductService;
import com.ncst.mvcweb.service.UserService;
import com.ncst.mvcweb.vo.JsonResult;
import com.ncst.mvcweb.vo.ShopCartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/shopcart")
public class ShopCartController {
    @Autowired
    private ProductService productService;
    @Autowired
    UserService userService;
    @Autowired
    ProductOrderService productOrderService;

    @GetMapping(value = "/list")
    public List<ShopCartItem> list(HttpSession session) {
        return getShopCart(session);
    }

    @PostMapping("deleteByList")
    public JsonResult deleteByList(@RequestParam("idList[]") List<Integer> idList, HttpSession session){

        List<ShopCartItem> shopCartItems = getShopCart(session);
        for (Integer id : idList) {
            for (int i = 0; i < shopCartItems.size(); i++) {
                if (id.equals(shopCartItems.get(i).getProductId())) {
                    shopCartItems.remove(i);
                    break;
                }
            }
        }
        return new JsonResult("success", "删除成功");
    }

    /**
     * 添加商品
     * @param idList 商品id
     * @param session session
     * @return
     */
    @PostMapping("add")
    public JsonResult save(@RequestParam("idList[]") List<Integer> idList, HttpSession session){
        for (Integer id : idList) {
            Product product = productService.queryById(id);
            // 判断商品是否存在
            boolean flag = false;
            // 判断商品是否存在
            if (product != null) {
                // 判断商品是否已经存在购物车中
                for (ShopCartItem item : getShopCart(session)) {
                    if (item.getProductId().equals(product.getId())) {
                        item.setCount(item.getCount() + 1);
                        flag = true;
                        break;
                    }
                }
                if (!flag){
                    ShopCartItem item = new ShopCartItem();
                    item.setProductId(product.getId());
                    item.setProductName(product.getProductName());
                    item.setPrice(product.getPrice());
                    item.setCount(1);
                    List<ShopCartItem> shopCartItems = getShopCart(session);
                    shopCartItems.add(item);
                }
            }
        }
        return new JsonResult("success", "添加成功");
    }

    private List<ShopCartItem> getShopCart(HttpSession session) {
        List<ShopCartItem> result = null;
        if (session.getAttribute("shopcart") == null) {
            result = new ArrayList<>();
            session.setAttribute("shopcart", result);
        }
        else
            result = (List<ShopCartItem>)session.getAttribute("shopcart");
        return result;
    }


    @PostMapping("/order")
    public JsonResult order(HttpSession session){
        if (session.getAttribute("loginUser") == null) {
            return new JsonResult("fail", "请先登录");
        }
        User user = (User)session.getAttribute("loginUser");

        List<ShopCartItem> shopCartItems = getShopCart(session);
        if (shopCartItems.isEmpty()) {
            return new JsonResult("fail", "购物车为空");
        }
        ProductOrder order = new ProductOrder();
        order.setOrderUser(user);
        order.setOrderTime(new Date());
        float total = 0.0f;
        List<OrderItem> items = new ArrayList<>();
        // 用于保存批量的商品信息
        List<Product> products = new ArrayList<>();
        for (ShopCartItem item : shopCartItems) {
            Product p = productService.queryById(item.getProductId());
            // 判断商品是否存在
            if (p == null)
                return new JsonResult("fail", "商品不存在");
            // 判断库存与购买量
            if (p.getCount() < item.getCount()) {
                return new JsonResult("fail", "库存不足");
            }

            // 当前商品添加进
            p.setCount(p.getCount() - item.getCount());
            products.add(p);

            OrderItem oi = new OrderItem();
            oi.setOrder(order);
            oi.setProduct(p);
            oi.setCount(item.getCount());
            oi.setPrice(p.getPrice());
            total += oi.getPrice() * oi.getCount().floatValue();
            items.add(oi);
        }
        // 批量保存商品---扣减库存
        productService.saveAll(products);
        order.setTotalMoney(total);
        productOrderService.save(order, items);
        shopCartItems.clear();
        return new JsonResult("success", "下单成功");
    }
}
